﻿using DryIoc.FastExpressionCompiler.LightExpression;
using MonitorPrism_Practice.Model;
using MonitorPrism_Practice.Mvvm;
using MonitorPrism_Practice.Services;
using MonitorPrism_Practice.ViewModel;
using MonitorPrism_Practice.Views.SettingConfig;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace MonitorPrism_Practice.ViewModels
{
    public class InterfaceWriteDataViewModel : BindableBase, IViewLoadedAndUnloadedAware
    {
        public IPlcService _plcService;
        private readonly IUndoRedoManager _undoManager;
        private IEventAggregator _aggregator { get; }


        private ObservableCollection<InterfaceWriteDataModel> _item = new ObservableCollection<InterfaceWriteDataModel>();
        public ObservableCollection<InterfaceWriteDataModel> Items
        {
            get { return _item; }
            set { SetProperty(ref _item, value); }
        }
      

        public InterfaceWriteDataViewModel(IUndoRedoManager undoManager,
            IPlcService plcService)
        {
            _item.Add(new InterfaceWriteDataModel() { Name = "温度", Address = "DBD82.DBDW38", DbIndex = 82, DbDataIndex = 38, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "功率", Address = "DBD63.DBDW154", DbIndex = 63, DbDataIndex = 154, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "目标温度", Address = "DBD63.DBDW20", DbIndex = 63, DbDataIndex = 24, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "功率上限", Address = "DBD63.DBDW88", DbIndex = 63, DbDataIndex = 88, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "积分隔离", Address = "DBD63.DBDW114", DbIndex = 63, DbDataIndex = 114, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "Kp", Address = "DBD63.DBDW0", DbIndex = 63, DbDataIndex = 0, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "Ki", Address = "DBD63.DBDW0", DbIndex = 63, DbDataIndex = 4, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _item.Add(new InterfaceWriteDataModel() { Name = "Kd", Address = "DBD63.DBDW0", DbIndex = 63, DbDataIndex = 8, DataType = S7.Net.VarType.Real, Command = WriteCommand });
            _undoManager = undoManager;
            _plcService = plcService;
            _aggregator = ContainerLocator.Current.Resolve<IEventAggregator>();
            _aggregator.GetEvent<WriteDataEvent>().Subscribe(AddItem);
        }
        private ICommand _writeCommand;
        public ICommand WriteCommand
        {
            get
            {
                return this._writeCommand ?? (this._writeCommand = new DelegateCommand<InterfaceWriteDataModel>((model) => {
                InterfaceWriteDataModel resModel =  ReadData(model);
                    _undoManager.Execute(
                    () => WriteData(model),
               () => WriteData(resModel),  // 撤销删除
               $"撤销了写入"  )// 操作描述

                  ;}));
            }
        }

        private ICommand _addItemCommand;
        public ICommand AddItemCommand
        {
            get
            {
                return this._addItemCommand ?? (this._addItemCommand = new DelegateCommand<InterfaceWriteDataModel>((model) => { AddItem(model); }));
            }
        }

        private ICommand _deleteItemCommand;
        public ICommand DeleteItemCommand
        {
            get
            {
                return this._deleteItemCommand ?? (this._deleteItemCommand = new DelegateCommand<InterfaceWriteDataModel>((item) =>
                {
                    MessageBoxResult result = System.Windows.MessageBox.Show(
                     $"确定要删除 {item.Name} 吗?",
                        "确认删除",
                         MessageBoxButton.YesNo,
                         MessageBoxImage.Question);
                    DeleteItem(item);
                }));
            }
        }
        private ICommand _openAddDadaViewCommand;
        public ICommand OpenAddDadaViewCommand
        {
            get
            {
                return this._openAddDadaViewCommand ?? (this._openAddDadaViewCommand = new DelegateCommand(() => { AddWriteDataView window = new AddWriteDataView(); window.Show(); }));
            }
        }
        private ICommand _undoCommand;
        public ICommand UndoCommand
        {
            get
            {
                return this._undoCommand ?? (this._undoCommand = new DelegateCommand(() => { Undo(); }));
            }
        }

        private ICommand _redoCommand;
        public ICommand RedoCommand
        {
            get
            {
                return this._redoCommand ?? (this._redoCommand = new DelegateCommand(() => { Redo(); }));
            }
        }

        private ICommand _clearUndoRedoCommand;
        public ICommand ClearUndoRedoCommand
        {
            get
            {
                return this._clearUndoRedoCommand ?? (this._clearUndoRedoCommand = new DelegateCommand(() => _undoManager.Clear()));
            }
        }
        private void Undo() => _undoManager.Undo();//撤销
        private void Redo() => _undoManager.Redo();//重做
        public void AddItem(InterfaceWriteDataModel item)
        {
            int index = Items.Count;
            if (index >= 0)
            {
                _undoManager.Execute(
                () => Items.Add(item),
                () => Items.RemoveAt(index),  // 撤销删除
                $"删除 {item.Name}"  // 操作描述

            );

            }
        }
        public void DeleteItem(InterfaceWriteDataModel item)
        {
            int index = Items.IndexOf(item);
            if (index >= 0)
            {
                _undoManager.Execute(
                () => Items.RemoveAt(index),
                () => Items.Insert(index, item),  // 撤销删除
                $"删除 {item.Name}"  // 操作描述
            );
            }
        }
        public void WriteData(InterfaceWriteDataModel model)
        {
            if (_plcService.IsConnected)
                _plcService.WriteData(model);
            else MessageBox.Show("写入失败，未连接");
        }
        public InterfaceWriteDataModel ReadData(InterfaceWriteDataModel model)
        {
            InterfaceReciveDataModel reciveDataModel = new InterfaceReciveDataModel()
            {
                Name = model.Name,
                DbIndex = model.DbIndex,
                DbDataIndex = model.DbDataIndex,
                DataType = model.DataType,
                Address = model.Address,
            };
            if (_plcService.IsConnected)
                _plcService.ReadData(reciveDataModel);
            model.Value = reciveDataModel.Value;
            return model;
        }

        public void OnLoaded(object sender, RoutedEventArgs e)
        {

        }

        public void OnUnloaded(object sender, RoutedEventArgs e)
        {
            _undoManager.Clear();
        }
    }
}
